<script setup lang="ts">
import { instance } from '@/utils/request'
import { useStorage } from '@vueuse/core'
import { ElMessageBox, ElNotification } from 'element-plus'
import { useLoadingStore } from '@/store/loading'

const { toggleLoading } = useLoadingStore()

const doorStatus = useStorage('door-status', [])

const getName = (id) => ({ 254: '走廊门', 255: '充电室门' })?.[id]

const getValue = (prop, val) => {
  const map = {
    0: ['已关闭', 'info'],
    1: ['已打开', 'success'],
    2: ['运动中', 'warning'],
    3: ['异常', 'danger'],
  }
  return map[prop]?.[val]
}

const doorControl = async (id, code) => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/code`,
      method: 'get',
      params: { id, code },
    })
    ElNotification({ type: 'success', title: '发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}
</script>

<template>
  <div class="common text-#96d8ff flex flex-col gap-4">
    <div class="title">自动门控制</div>
    <div v-for="item in doorStatus" :key="item.id" class="flex gap-2 items-center">
      <div class="w-20 text-right">{{ getName(item.id) }}：</div>
      <ElTag :type="getValue(item.status, 1)">{{ getValue(item.status, 0) }}</ElTag>
      <ElButtonGroup>
        <ElButton
          size="small"
          :plain="true"
          type="primary"
          @click="doorControl(item.id, 1)"
          :disabled="item.status === 1"
        >
          打开
        </ElButton>
        <ElButton
          size="small"
          :plain="true"
          type="danger"
          @click="doorControl(item.id, 0)"
          :disabled="item.status === 0"
        >
          关闭
        </ElButton>
      </ElButtonGroup>
    </div>
  </div>
</template>
